// 参考博客文章 https://blog.csdn.net/qq_61798776/article/details/139913530
import ffmpeg from "fluent-ffmpeg";
import axios from "axios";
import { PassThrough } from "stream";
/**
 * 提取 .MP3 文件流
 * @param {*} silkFileUrl .silk 远程路径地址
 * @returns 获取到的 .mp3 文件流
 */
export async function getMp3Stream(silkFileUrl) {
  try {
    const mp3Stream = await convertSilkToMp3(silkFileUrl);
    return mp3Stream;
  } catch (error) {
    console.error(`Failed to convert: ${error.message}`);
  }
}

/**
 * .silk --> .mp3
 * @param {*} silkFileUrl .silk 线上路径地址
 * @returns ffmpeg转换后结果
 */
async function convertSilkToMp3(silkFileUrl) {
  // 下载 .silk 文件
  const response = await axios({
    method: "get",
    url: silkFileUrl,
    responseType: "arraybuffer",
  });

  // console.log("convertSilkToMp3.convertSilkToMp3: ", response);
  // console.log("ffmpeg工具包: ", ffmpeg);
  const silkBuffer = Buffer.from(response.data); // 创建 Buffer
  const passThrough = new PassThrough();
  console.log("silkBuffer文件流: ", silkBuffer);
  // 将 Buffer 写入 PassThrough 流
  passThrough.end(silkBuffer); // 将 Buffer 写入流并结束流
  // 创建一个新的 PassThrough 流用于输出转换后的 MP3
  const outputPassThrough = new PassThrough();
  // 使用 ffmpeg 进行转换
  ffmpeg(passThrough)
    .inputFormat("silk") // 指定输入格式
    .toFormat("mp3")
    .on("end", () => {
      console.log("Conversion finished");
    })
    .on("error", (err) => {
      console.error(`Error during conversion: ${err.message}`);
    })
    .pipe(outputPassThrough, { end: true });
  return outputPassThrough;
}
